package com.hmsm.sys.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.hmsm.server.base.BaseService;
import com.hmsm.sys.dao.UserRoleDao;
import com.hmsm.sys.dto.UserDto;
import com.hmsm.sys.po.RoleInfo;
import com.hmsm.sys.po.UserInfo;
import com.hmsm.sys.po.UserRole;

/**
 * 用户权限控制
 * 
 * @author 舒俊
 *
 *@version 1.0, 2012-11-25 上午11:43:29
 */
@Service
public class UserRoleService extends BaseService<UserRole, Integer, UserInfo, RoleInfo> implements IUserRoleService {

	private static final Log log = LogFactory.getLog(UserRoleService.class);
	
	public UserRoleDao getUserRoleDao() {
		return (UserRoleDao) baseDao;
	}

	@Resource
	public void setUserRoleDao(UserRoleDao userRoleDao) {
		this.baseDao = userRoleDao;
	}

	/**
	 * 根据用户ID，获取所有的用户角色信息
	 * @param userId
	 * @return
	 * @author 舒俊
	 */
	public List<UserRole> getUserRoleByUserList(int userId){
		UserRole userRole = new UserRole();
		userRole.setUserId(userId);
		userRole.setState(1);
		return getUserRoleDao().query(userRole);
	}
	
	/**
	 * 获取角授权列表
	 * @param userId
	 * @return
	 * @author 舒俊
	 */
	public List<UserRole> getUserRoleByRoleId(int roleId){
		UserRole userRole = new UserRole();
		userRole.setRoleId(roleId);
		userRole.setState(1);
		return getUserRoleDao().query(userRole);
	}
	
	/**
	 * 清空角授权用户列表
	 * @param userId
	 * @return
	 * @author 舒俊
	 */
	public void cleanRoleUsersByRoleId(Integer roleId){
		UserRole userRole = new UserRole();
		userRole.setRoleId(roleId);
		userRole.setState(1);
		List<UserRole> list = getUserRoleDao().query(userRole);
		for(UserRole ur:list){
			getUserRoleDao().delete(ur);
		}
	}
	
	/**
	 * 获取角授权列表
	 * @param userId
	 * @return
	 * @author 舒俊
	 */
	public void delUserRoleByRoleId(int roleId){
		List<UserRole> list = getUserRoleByRoleId(roleId);
		for(UserRole userRole:list){
			getUserRoleDao().delete(userRole);
		}
	}
	
	/**
	 * 根据角色ID获取用户
	 * @param roleId
	 * @return
	 * @author 舒俊
	 */
	@SuppressWarnings("static-access")
	public List<UserDto> getRoleUserRelationByRole(int roleId){
		return this.getUserRoleDao().queryUserRoleByRoleId(roleId);
	} 
	
	/**
	 * 解除角色和用户的关联
	 * @param roleId
	 * @param userId
	 * @author 舒俊
	 */
	public void unbindUserRoleRelation(Integer roleId, Integer userId){
		UserRole userRole = new UserRole();
		userRole.setRoleId(roleId);
		userRole.setUserId(userId);
		userRole.setState(1);
		List<UserRole> userRoleList =  getUserRoleDao().query(userRole);
		for(int i=0;i<userRoleList.size();i++){
			userRole = userRoleList.get(i);
			userRole.setState(2);
			try {
				delete(userRole);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 绑定用户和角色的关联关系
	 * @param userId
	 * @param roleId
	 * @author 舒俊
	 * @throws Exception 
	 */
	public void bindUserRoleRelation(Integer userId, Integer roleId) throws Exception{
		UserRole userRole = new UserRole();
		userRole.setRoleId(roleId);
		userRole.setUserId(userId);
		userRole.setState(1);
		List<UserRole> userRoleList =  getUserRoleDao().query(userRole);
		if(userRoleList.size()==0){
			//绑定关系不存在，新增该信息
			this.save(userRole);
		}else{
			this.log(this,"用户："+userId+" 角色："+roleId+" 已关联，不需要重复关联.");
		}
	}

	public List<Integer> getRoleIdsByUserId(Integer userId) {
		List<Integer> userRoleIds = null;

		UserRole userRole = new UserRole();
		userRole.setState(1);
		userRole.setUserId(userId);

		List<UserRole> list = getUserRoleDao().query(userRole);
		userRoleIds = new ArrayList<Integer>();
		for (UserRole ur : list) {
			userRoleIds.add(ur.getRoleId());
		}

		return userRoleIds;
	}

	public Set<Integer> getUserIdsByRoleId(Integer roleId) {
		Set<Integer> roleUserIds = new HashSet<Integer>();
		
		UserRole example = new UserRole();
		example.setRoleId(roleId);
		example.setState(1);
		List<UserRole> userRoleList = baseDao.query(example);
		for(UserRole userRole:userRoleList){
			if(!roleUserIds.contains(userRole.getUserId())){
				roleUserIds.add(userRole.getUserId());
			}
		}
		
		return roleUserIds;
	}

	public UserRole update(UserRole ur) {
		return baseDao.update(ur);
	}

	public void updateUserRoles(UserInfo userInfoPo) {
		UserRole example = new UserRole();
		example.setUserId(userInfoPo.getPkId());
		List<UserRole> userRoleList = baseDao.query(example);
		// 删除要删除的角色授权

		List<Integer> ids = userInfoPo.getRoleIds();
		for (UserRole userRole : userRoleList) {
			Integer findRoleId = null;
			for (Integer roleId : ids) {
				if (userRole.getRoleId().equals(roleId)) {
					// 找到一个要保留的
					findRoleId = roleId;
					break;
				}
			}
			if (findRoleId != null) {
				// 找到的，不用再处理了
				ids.remove(findRoleId);
			} else {
				// 没找到，应删除
				baseDao.delete(userRole);
			}
		}
		// 添加没有的
		for (Integer id : ids) {
			UserRole userRole = new UserRole();
			userRole.setUserId(userInfoPo.getPkId());
			userRole.setRoleId(id);
			baseDao.save(userRole);
		}
	}

}
